package com.pq.controller;

import com.pq.dao.user.UserDao;
import com.pq.pojo.user.User;
import com.pq.utils.CookieUtil;
import com.pq.utils.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class IndexController {
    // 使用常量定义cookie名称
    private static final String PQ_TICKET = "PQ_TICKET";

    @Autowired
    private Jedis jedis;
    @GetMapping("/index")
    public String getIndex() {
        return "index";
    }
    @GetMapping("/doDrop")
    public String doDrop(HttpServletRequest request, HttpServletResponse response){
        String ticket = CookieUtil.getCookieValue(request, PQ_TICKET);
        if (StringUtils.hasLength(ticket)){
            jedis.del(ticket);
            CookieUtil.addCookie(response,PQ_TICKET,"","/","pq.com",0);
        }
        return "login";
    }
    @GetMapping("/aboutme")
    public String doAboutme(HttpServletRequest request, Model model){
        String ticket = CookieUtil.getCookieValue(request, PQ_TICKET);
        if (!StringUtils.hasLength(ticket))
            return "login";
        String json = jedis.get(ticket);
        User user = ObjectMapperUtil.toObject(json, User.class);
        model.addAttribute("username", user.getUserName());
        return "aboutme";
    }

    @GetMapping("/regit")
    public String doRegit(){
        return "regit";
    }

    @GetMapping("/ordercart")
    public String orderCart() {
        return "ordercart";
    }

    @GetMapping("login")
    public String doLogin(){
        return "login";
    }

}
